// pages/settlement/index.js
const moment = require('moment')
Page({

    /**
     * 页面的初始数据
     */
    data: {
        defaultaddress: null,
        storeList: [],
        priceData: null,
        isOrder: false, //是否普通下单
        couponList: [],
        radio: '',
        couponShow: false
    },
    params: {},
    couponPage: 1,
    couponLoading: false,
    finish: false,
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let {
            // 普通下单
            cart_ids,
            receive_id,
            // 兑换下单
            product_id,
            stock_id,
            quantity,
            address_id
        } = options
        Object.assign(this.params, options)
        if (cart_ids) {
            this.setData({
                isOrder: true
            })
            this.getSettlement()
        } else {
            this.getProductinfo()
        }
        this.getdefaultaddress()
    },
    /**
     * 获取兑换商品
     */
    getProductinfo() {
        wx.http.post(wx.api.productinfo, {
            product_id: this.params.product_id
        }).then(res => {
            if (res.code == 1) {
                let {
                    shop,
                    product
                } = res.data
                shop.imagesurl = `${wx.api.host}/${shop.imagesurl}`
                product.imageurl = `${wx.api.host}/${product.imageurl}`
                let storeList = [Object.assign(shop, {
                    product: [product]
                })]
                this.setData({
                    storeList
                })
            }
        })
    },
    /**
     * 兑换
     */
    onExchange() {
        let {
            product_id,
            stock_id,
            quantity
        } = this.params
        if (!this.data.defaultaddress) {
            return wx.showToast({
                title: '请选择地址',
                icon: "none"
            })
        }
        let {
            address_id
        } = this.data.defaultaddress

        console.log('兑换下单参数', {
            product_id,
            stock_id,
            quantity,
            address_id,
        });

        wx.http.post(wx.api.uncommonplace, {
            product_id,
            stock_id,
            quantity,
            address_id,
        }).then(res => {
            if (res.code == 1) {
                wx.showToast({
                    title: '兑换成功',
                    icon: 'success',
                    duration: 1000,
                    mask: true
                })
                setTimeout(() => {
                    console.log('跳转');
                    // wx.navigateTo({
                    //   url: 'url',
                    // })
                }, 1000)
            }
        })
    },
    /**
     * 选择优惠卷
     */
    jump() {
        // let query = []
        // for (const key in this.params) {
        //     let value = this.params[key]
        //     query.push(key + '=' + value);
        // }
        // wx.navigateTo({
        //     url: `/pages/consum/index?${query.join('&')}`,
        // })
        this.setData({
            couponShow: false,
            couponList: [],

        })
        this.couponPage = 1
        this.getUsercouponlist()


    },
    /**
     * 获取普通下单结算
     */
    getSettlement() {
        let {
            cart_ids,
            receive_id
        } = this.params
        let {
            radio
        } = this.data
        wx.http.post(wx.api.Settlement, {
            cart_ids,
            receive_id: receive_id || ''
        }).then(res => {
            if (res.code == 1) {
                let list = res.data.list.map(t => Object.assign(t, {
                    imagesurl: `${wx.api.host}/${t.imagesurl}`,
                    product: t.product.map(item => Object.assign(item, {
                        imageurl: `${wx.api.host}/${item.imageurl}`
                    }))
                }))
                let priceData = res.data.price
                priceData.pay_amountInt = priceData.pay_amount.split('.')[0]
                priceData.pay_amountFloor = priceData.pay_amount.split('.')[1]
                if (!res.data.is_coupon) {
                    wx.showToast({
                        title: '优惠券不可用',
                        icon: "error"
                    })
                    this.params.receive_id = undefined
                    radio = ''
                }
                this.setData({
                    storeList: list,
                    priceData: res.data.price,
                    couponShow: false,
                    radio
                })
            }
        })
    },
    /**
     * 普通商品下单
     */
    onPay() {
        let {
            cart_ids,
            receive_id,
        } = this.params
        if (!this.data.defaultaddress) {
            return wx.showToast({
                title: '请选择地址',
                icon: "none"
            })
        }
        let {
            address_id
        } = this.data.defaultaddress
        let orderId = ''
        wx.showLoading({
            title: '加载中...',
        })
        wx.http.post(wx.api.GoToPlace, {
            cart_ids,
            receive_id: receive_id || '',
            address_id,
            pay_end: 2
        }).then(res => {
            const {
                nonceStr,
                package: pa,
                paySign,
                timeStamp,
                signType
            } = res.data
            orderId = res.data.data.order_id
            wx.hideLoading()
            return wx.requestPayment({
                nonceStr,
                package: pa,
                paySign,
                timeStamp,
                signType
            })
        }).then(res => {
            wx.redirectTo({
                url: `/pages/payRes/index?order_id=${orderId}`,
            })
        }).catch(err => {
            console.error(err);
            wx.showToast({
                title: '支付失败',
                icon: 'error',
                mask: true
            })
            setTimeout(() => {
                wx.redirectTo({
                    url: '/packageA/order/index?status=1',
                })
            }, 1000)
        })
    },
    /**
     * 获取消费卷
     */
    getUsercouponlist() {
        this.couponLoading = true
        let {
            couponShow,
            couponList
        } = this.data
        wx.http.get(wx.api.usercouponlist, {
            page: this.couponPage
        }).then(res => {
            let list = res.data.data.map(t => ({
                ...t,
                discount: Number(t.discount),
                use_stime: moment(t.use_stime * 1000).format('YYYY年MM月DD日'),
                use_etime: moment(t.use_etime * 1000).format('YYYY年MM月DD日')
            }))
            this.couponLoading = false
            if (this.couponPage == 1 && list.length == 0) {
                couponShow = false
                wx.showToast({
                    title: '无消费卷可用',
                    icon: 'none'
                })
            }
            couponShow = true
            this.setData({
                couponShow,
                couponList: couponList.concat(list)
            })
        })
    },
    /**
     * 选择优惠券
     */
    onCunpon(e) {
        const {
            receive_id
        } = e.currentTarget.dataset
        console.log(receive_id, e);
        this.setData({
            radio: receive_id
        })
        this.params.receive_id = receive_id
        this.getSettlement()
    },
    onCouponClose() {
        this.setData({
            couponShow: false
        })
    },
    /**
     * 消费卷滚动到顶部
     */
    onScrolltolower() {
        this.couponPage += 1
        if (!this.couponLoading) {
            this.getUsercouponlist()
        }
    },
    /**
     * 获取默认收货地址
     */
    getdefaultaddress() {
        wx.http.post(wx.api.getdefaultaddress).then(res => {
            let defaultaddress = res.data
            let {
                province_name,
                city_name,
                area_name,
                detail
            } = defaultaddress
            defaultaddress.address_detail = province_name + city_name + area_name + detail
            this.setData({
                defaultaddress
            })
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        // if (this.data.isOrder) {
        //     this.getSettlement()
        // }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },
})